package main.java.com.itlin.datastructure.deque;


import java.util.Iterator;

/**
 * 基于循环数组实现，特点
 * * tail 停下来的位置不会存储，会浪费一个位置
 * @param <E> -> 队列中的元素类型
 */
public class ArrayDeque1<E> implements Deque<E>,Iterable<E>{

    /*
     * h - head
     * t - tail
     * 注意：还是 tail指针位置没有元素
     * h
     *   t
     * 0 1 2 3 4
     * a
     * offerLast(a) -> 先添加元素，再tail++
     * offerFirst(c) -> 先head--，再添加元素
     *
     *
     * 添加两个工具方法 防止索引越界
     */

    /**
     * 指针右移
     * @param i
     * @param length
     * @return
     */
    static int inc(int i, int length){
        if (i + 1 >= length) return 0;
        return i + 1;
    }

    /**
     * 指针左移
     * @param i
     * @param length
     * @return
     */
    static int dec(int i, int length){
        if (i - 1 < 0) return length - 1;
        return i - 1;
    }

    /**
     * 添加实现类的属性和构造器
     */
    E[] array;
    private int head;
    private int tail;

    @SuppressWarnings("all")
    public ArrayDeque1(int capacity){
        array = (E[])new Object[capacity + 1];

    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            int p = head;
            @Override
            public boolean hasNext() {
                return p != tail;
            }

            @Override
            public E next() {
                E e = array[p];
                p = inc(p, array.length);
                return e;
            }
        };
    }

    @Override
    public boolean offerFirst(E e) {
        if (isFull()) return false;
        head = dec(head, array.length);
        array[head] = e;
        return true;
    }

    @Override
    public boolean offerLast(E e) {
        if (isFull()) return false;
        array[tail] = e;
        tail = inc(tail, array.length);
        return true;
    }

    @Override
    public E pollFirst() {
        if (isEmpty()) return null;
        E e = array[head];
        array[head] = null;//help GC
        head = inc(head, array.length);
        return e;
    }

    @Override
    public E pollLast() {
        if (isEmpty()) return null;
        tail = dec(tail,array.length);
        E e = array[tail];//help GC
        array[tail] = null;
        return e;
    }

    @Override
    public E peekFirst() {
        if (isEmpty()) return null;
        E e = array[head];
        return e;

    }

    @Override
    public E peekLast() {
        if (isEmpty()) return null;
        E e = array[dec(tail,array.length)];
        return e;

    }

    @Override
    public boolean isEmpty() {

        return head == tail;
    }

    @Override
    public boolean isFull() {
        if (head > tail) return head - tail == 1;
        if (head < tail) return tail - head == array.length - 1;
        else return false;
    }
}
